package src.mysql;

import src.config.SysConfig;

import java.sql.*;

/**
 * @author CsCN
 */
public class MysqlHelper {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    /**
     * 最后一项是选择数据库
     */
    private static final String DB_URL = "jdbc:mysql://"
            + SysConfig.MYSQL_IP + ":" + SysConfig.MYSQL_PORT + "/" + SysConfig.MYSQL_DATABASE
            + "?useSSL=false";
    private static final String USER = SysConfig.MYSQL_USERNAME;
    private static final String PASS = SysConfig.MYSQL_PASSWORD;
    protected Connection connection = null;

    public MysqlHelper() {
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);
            // 打开链接
            System.out.println("连接数据库...");
            connection = DriverManager.getConnection(DB_URL, USER, PASS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取预编译的sql语句
     *
     * @param sql sql语句
     * @return 预编译后的sql语句
     */
    public PreparedStatement getPreparedStatement(String sql) {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return preparedStatement;
    }

    /**
     * 执行原始的sql语句(未预编译)
     *
     * @param sql sql语句
     */
    public void executeRaw(String sql) {
        System.out.println("executeRaw: " + sql);
        try {
            Statement statement = null;
            statement = connection.createStatement();
            statement.execute(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询一样东西
     *
     * @param sql         sql语句
     * @param columnLabel 列名
     * @return 查询结果String, 没有则返回null
     */
    public String queryOnce(String sql, String columnLabel) {
        System.out.println("queryOnce: " + sql);
        String res = null;
        try (Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {
            if (resultSet.next()) {
                res = resultSet.getString(columnLabel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }


}
